package com.wyy.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyy.mapper.CommentsMapper;
import com.wyy.mapper.UserMapper;
import com.wyy.pojo.Comments;
import com.wyy.pojo.Users;
import com.wyy.pojo.model.CommentModel;
import com.wyy.pojo.model.CommentQuery;
import com.wyy.pojo.model.UserToken;
import com.wyy.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: gytcb
 * @author: 吴磊
 * @create: 2021-06-08 18:21
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> getAllComment(CommentQuery commentQuery) {

        int curPage = commentQuery.getCurPage();

        HashMap<String, Object> map = new HashMap<>();
        //分页，根据前端传过来的 p 页数
        Page<Comments> page = new Page<>(curPage, 10);
        //总篇数
        long total;
        //总页数
        long pages;
        List<Comments> comments;
        Page<Comments> usersPage = commentsMapper.selectPage(page, null);
        pages = usersPage.getPages();
        total = usersPage.getTotal();
        comments = usersPage.getRecords();
        List<CommentModel> commentModels = comments.stream().map(comment -> {
            CommentModel model = new CommentModel();
            String userId = comment.getUserId();
            Users user = userMapper.getUserById(userId);
            UserToken userToken = new UserToken();
            BeanUtils.copyProperties(user, userToken);
            BeanUtils.copyProperties(comment, model);
            model.setUserToken(userToken);
            return model;
        }).collect(Collectors.toList());

        //总篇数
        map.put("total", total);
        //总页数
        map.put("pages", pages);
        //文章 <=10篇
        map.put("comments", commentModels);
        return map;
    }

    @Override
    public void deleteCommentById(String commentId) {
        String commentId1 = JSON.parseObject(commentId, Comments.class).getCommentId();
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        wrapper.eq("comment_id", commentId1);
        commentsMapper.delete(wrapper);
    }
}
